package com.example.mysaat.service_menu_manual_test.allActivities;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.nfc.NfcAdapter;
import android.nfc.NfcManager;
import android.nfc.Tag;
import android.nfc.tech.NfcA;
import android.os.Build;
import android.os.Bundle;
import android.se.omapi.Channel;
import android.se.omapi.Reader;
import android.se.omapi.SEService;
import android.se.omapi.Session;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.mysaat.R;
import com.example.mysaat.service_menu_manual_test.Listeners.MyFailOnclickListener;
import com.example.mysaat.service_menu_manual_test.Listeners.MyPassOnclickListener;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RequiresApi(api = Build.VERSION_CODES.P)
public class NFCActivity extends AppCompatActivity implements SEService.OnConnectedListener{
    private SEService seService = null;
    private NfcManager nfcManager = null;
    private NfcAdapter nfcAdapter = null;
    private IntentFilter[] intentFiltersArray;
    private PendingIntent pendingIntent = null;
    private TextView reader_textView = null;
    private TextView swp_textView = null;
    private Button pass_btn = null;
    private Button fail_btn = null;
    private Button start_btn = null;
    private static final String TAG = "NFCActivity";
    @RequiresApi(api = Build.VERSION_CODES.P)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nfc);
        init();
        initContent();
        if(nfcManager!=null){
            nfcAdapter = nfcManager.getDefaultAdapter();
        }else{
            nfcAdapter = NfcAdapter.getDefaultAdapter(NFCActivity.this);
        }
        if(nfcAdapter==null){
            Log.d(TAG, "nfcAdapter is null ");
        }else{
            if(!nfcAdapter.isEnabled()){
                try {
                    Method method = NfcAdapter.class.getDeclaredMethod("enable");
                    method.setAccessible(true);
                    method.invoke(nfcAdapter);
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
            pendingIntent = PendingIntent.getActivity(this,0,new Intent(this,getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),0);
            Log.d(TAG, "nfcAdapter is not null"+pendingIntent);
            try{
                IntentFilter ndefIntentFilter = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED,"*/*");
                IntentFilter techIntentFilter = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
                IntentFilter tagIntentFilter = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
                intentFiltersArray = new IntentFilter[]{ndefIntentFilter,techIntentFilter,tagIntentFilter};
            }catch (IntentFilter.MalformedMimeTypeException e){
                Log.e(TAG, "MIME type syntax error : " + e);
            }
        }
        try{
            ExecutorService executors = Executors.newSingleThreadExecutor();
            seService = new SEService(this,executors,this);
        }catch (SecurityException e){
            Log.d(TAG, "Binding not allowed,user-permission org.simalliance.openmobileapi.SMARTCARD?"+e.getMessage());
        }catch (Exception e){
            Log.e(TAG, "exception"+e.getMessage());
        }




    }

    private void init(){
        pass_btn = findViewById(R.id.nfc_pass_btn);
        fail_btn = findViewById(R.id.nfc_fail_btn);
        start_btn = findViewById(R.id.nfc_start_btn);
        reader_textView = findViewById(R.id.nfc_reader_result_tv);
        swp_textView = findViewById(R.id.nfc_swp_result_tv);
        nfcManager = (NfcManager)getSystemService(NFC_SERVICE);
    }

    private  void initContent(){
        pass_btn.setOnClickListener(new MyPassOnclickListener(NFCActivity.this,null));
        fail_btn.setOnClickListener(new MyFailOnclickListener(NFCActivity.this,null));
        start_btn.setEnabled(false);
        start_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(NFCActivity.this,"请重新测试",Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(nfcAdapter!=null)
            nfcAdapter.disableForegroundDispatch(this);     //取消调度
    }


    @Override
    protected void onResume() {
        super.onResume();
        if(nfcAdapter!=null) {
//            这行代码是添加调度，效果是读标签的时候不会弹出候选程序，直接用本程序处理
            nfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, null);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        seService.shutdown();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        String action = intent.getAction();
        if(NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)){
            //处理扫描到的NFC标签中的数据
            Tag tagId = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

            try {
                Log.d(TAG+"查看支持的技术",tagId.getTechList()[0]+"*"+tagId.getTechList()[1]+"*"+tagId.getTechList()[2]);
                NfcA dep = NfcA.get(tagId);
                if(dep==null) return;
                dep.connect();
                byte[]request = new byte[]{
                        (byte)0x00,
                        (byte)0X20,
                        (byte)(0&0xff)
                };
                byte [] datas = dep.transceive(request);
                Log.d(TAG, "onNewIntent: "+"执行到了"+dep.transceive(request)[0]);
                //在页面给出测试的答案
                if(tagId!=null){
                    reader_textView.setText("Pass");
                }else {
                    reader_textView.setText("Fail");
                    reader_textView.setBackgroundColor(Color.RED);
                    start_btn.setEnabled(true);
                    return;
                }
/*-------------------------------------------链接SIM卡的服务----------------------------------------------------------------*/
                Session session = null;
                Reader reader = null;
                try {
                    if(seService.isConnected()){
                        reader = seService.getReaders()[0];
                        session = reader.openSession();
                        //在此个测试之中缺少一个aid的byte[],已经可以连接了
                        //下一步找到一个aid的byte[]数组和SIM卡获取连接channel对象即可
                        byte[] bytes = "A000000333010106".getBytes();
                        Channel channel = session.openLogicalChannel(null);
                        if(channel==null){
                            Toast.makeText(NFCActivity.this,"输入正确的AID的byte数组",Toast.LENGTH_SHORT).show();
                            //现在默认这个情况是完成的情况
                            swp_textView.setText("Pass");
                            start_btn.setEnabled(false);
                            pass_btn.setEnabled(true);
                        }else{
                            swp_textView.setText("Fail");
                            swp_textView.setTextColor(Color.BLUE);
                            swp_textView.setBackgroundColor(Color.RED);
                            start_btn.setEnabled(true);
                            channel.transmit(datas);
                            channel.close();
                        }
                    }
                } catch (IOException e) {
                    Log.d(TAG, "IO链接错误  请检查相关的连接 或者是byte[]");
                }finally {
                    session.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public void finish() {
        super.finish();
        if(nfcAdapter!=null&&nfcAdapter.isEnabled()){
            try {
               Method method = NfcAdapter.class.getDeclaredMethod("disable");
                method.setAccessible(true);
                method.invoke(nfcAdapter);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }


    private String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();

        if (src == null || src.length <= 0) {
            return null;
        }
        char[] buffer = new char[2];
        for (int i = 0; i < src.length; i++) {
            buffer[0] = Character.toUpperCase(Character.forDigit(
                    (src[i] & 0xF0)>>>4, 16));
            buffer[1] = Character.toUpperCase(Character.forDigit(src[i] & 0x0F,
                    16));
            System.out.println(buffer);
            stringBuilder.append(buffer);
        }
        return stringBuilder.toString();
    }


    @Override
    public void onConnected() {
        Log.d(TAG, "onConnected: SEService is connected ");
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {
        Log.d(TAG, "onPointerCaptureChanged: "+hasCapture);
    }
}




